--
-- Created by IntelliJ IDEA.
-- User: bluda
-- Date: 2018/9/8
-- Time: 18:07
-- To change this template use File | Settings | File Templates.
-- 寻路功能

local FindPath = {}

local tx = {
    [0] = {c=1, r=0},
    [1] = {c=1, r=1},
    [2] = {c=0, r=1},
    [3] = {c=-1, r=1},
    [4] = {c=-1, r=0},
    [5] = {c=-1, r=-1},
    [6] = {c=0, r=-1},
    [7] = {c=1, r=-1},
}

-- 当没有路径得时候，返回nil, 否则返回角度
-- localUnit: 战斗单元
-- targetPosition: 目标像素位置
-- targetGrid: 目标位置
-- grid: 二维数组地图格子
function FindPath:find(localUnit, targetPosition, targetGrid, grid)
    local angle = angle(localUnit.position, targetPosition)
--    if angle ~= nil then
--        
--        return angle
--    end
    --logW("angle = " .. angle)
    local index = -1

    local corArea = angle / 45 + 0.5
    if corArea >= 8 or corArea < 1 then
        index = 0
    else
        index = math.floor(corArea)
    end

    -- 如果目标格子和当前格子相差1，那么判断是否能过去
    local dxt = distance4(localUnit.grid.c, localUnit.grid.r, targetGrid.c, targetGrid.r)
    if (dxt >= 1 and dxt <= 2 and dxt > 1000) or dxt == 0 then
        return nil    
    end

    local dst = -1
    local retTbl = {}
    if angle > 90 then
        for i = 0, 7 do
            local c = localUnit.grid.c + tx[index].c
            local r = localUnit.grid.r + tx[index].r
            --logW("c =  " .. c, " r = " .. r)
            if c > 0 and c <= BATTELFIELD_GRID and r > 0 and r <= BATTELFIELD_GRID and grid[r][c].v <= 1000 then
                local newDst = distance4(c, r, targetGrid.c, targetGrid.r)
                if newDst < dst or dst == -1 then
                    dst = newDst
                    retTbl.index = index
                    retTbl.c = c
                    retTbl.r = r
                end
            end
    
            index = index + 1
            if index > 7 then
                index = 0
            end
        end
    else
        for i = 0, 7 do
            local c = localUnit.grid.c + tx[index].c
            local r = localUnit.grid.r + tx[index].r
            --logW("c =  " .. c, " r = " .. r)
            if c > 0 and c <= BATTELFIELD_GRID and r > 0 and r <= BATTELFIELD_GRID and grid[r][c].v <= 1000 then
                local newDst = distance4(c, r, targetGrid.c, targetGrid.r)
                if newDst < dst or dst == -1 then
                    dst = newDst
                    retTbl.index = index
                    retTbl.c = c
                    retTbl.r = r
                end
            end

            index = index - 1
            if index < 0 then
                index = 7
            end
        end
    end
    if retTbl.index ~= nil then
        --logW("return angle " .. (retTbl.index * 45 - 22.5), retTbl.c, retTbl.r)
        return retTbl.index * 45, retTbl.c, retTbl.r
    end
    
    return nil
end



return FindPath